package com.pt25.base.model.websocket.handler;


import com.pt25.base.model.websocket.WebsocketHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ChannelHandler.Sharable
public class HeartbeatHandler extends ChannelInboundHandlerAdapter {

    @Resource
    private WebsocketHandler websocketHandler;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        // 监听 IdleStateEvent 事件
        if (evt instanceof IdleStateEvent event) {
            if (event.state() == IdleState.READER_IDLE) {
                log.info("心跳超时，关闭连接, id={}", ctx.channel().id().asLongText());
                websocketHandler.handleHeartbeat(ctx, 1);
                ctx.close(); // 关闭超时连接
            }
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 响应 WebSocket Ping 帧（自动回复 Pong）
        if (msg instanceof PingWebSocketFrame) {
            ctx.writeAndFlush(new PongWebSocketFrame());
            websocketHandler.handleHeartbeat(ctx, 0);
            return;
        }
        ctx.fireChannelRead(msg); // 传递给下一个处理器
    }
}
